﻿using System.Collections.Generic;
using Bingosoft.Data;
using Bingosoft.Data.Sql;
using Bingosoft.Modules.SecurityConsole.Common.Helper;

namespace Bingosoft.Modules.SecurityConsole.Common.FunctionControl.TreeListSelect
{
    public class TreeListSelectService : ITreeListSelectService
    {
        private readonly Dao dao = Dao.Get();

        public IList<IDictionary<string, object>> LoadData(string sqlId, string parameters)
        {
            IDictionary<string, object> dictionary = DictionaryHelper.ConvertJsonStringToDictionary(parameters);
            int currentPage = DictionaryHelper.GetParamInt(dictionary, "currentPage");
            int pageSize = DictionaryHelper.GetParamInt(dictionary, "pageSize");

            IList<IDictionary<string, object>> dataList = dao.PageQueryDictionaries(sqlId, (pageSize*(currentPage - 1) + 1), pageSize, "NAME", dictionary);
            return dataList;
        }

        public int GetPageInfo(string sqlId, string parameters)
        {
            IDictionary<string, object> dictionary = DictionaryHelper.ConvertJsonStringToDictionary(parameters);
            ISqlStatement statement = DaoFactory.GetSqlSource().Find(sqlId);

            string newText = dao.Provider.WrapCountSql(statement.Text);

            ISqlStatement newStatement = SqlParser.Parse(newText, false);

            ISqlCommand command = newStatement.CreateCommand(dictionary);

            int totalSize = dao.QueryScalar<int>(command.CommandText,dictionary);
            return totalSize;
        }
    }
}
